package com.wbs.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wbs.mapper.TbAddressMapper;
import com.wbs.model.*;
import com.wbs.service.AddressService;
import com.wbs.vo.AddressVO;
import com.wbs.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 芝梦
 * @Description:
 * @DateTime: 2024/2/27 15:27
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private TbAddressMapper tbAddressMapper;

    //选择按用户名获取地址
    @Override
    public List<AddressVO> selectAddressByUsername(String username) {
        AddressVO addressVO = new AddressVO();
        addressVO.setUserId(username);

        //根据UserId条件查询
        List<TbAddress> tbAddresses = tbAddressMapper.selectByExample(this.buildExample(addressVO));

        //转换集合VO
        return tbAddresses.stream().map(this::convertVo).collect(Collectors.toList());
    }

    //通过id查询地址信息
    @Override
    public TbAddress selectAddrById(Long id) {
        return tbAddressMapper.selectByPrimaryKey(id);
    }

    /*辅助方法----------------------------------------------------------------------------------------*/

    //构建条件类
    private TbAddressExample buildExample(AddressVO addressVO) {
        TbAddressExample tbAddressExample = new TbAddressExample();
        TbAddressExample.Criteria criteria = tbAddressExample.createCriteria();
        //根据userid查询
        if (!addressVO.getUserId().isEmpty()){
            criteria.andUserIdEqualTo(addressVO.getUserId());
        }
        return tbAddressExample;
    }

    //转换为VO
    private AddressVO convertVo(TbAddress tbAddress) {
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(tbAddress, addressVO);
        return addressVO;
    }
    //转换为Tb
    private TbAddress convertVo(AddressVO addressVO) {
        TbAddress tbAddress = new TbAddress();
        BeanUtils.copyProperties(addressVO, tbAddress);
        return tbAddress;
    }
}
